package io.gitee.jingtuo.android.device.ui.search.prop

import androidx.lifecycle.ViewModel
import io.gitee.jingtuo.android.device.SysProManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

/**
 * 搜索属性的ViewModel
 */
class SearchPropViewModel : ViewModel() {

    private val searchResult = MutableStateFlow(SysProManager.getProperties())

    fun search(text: String) {
        if (text.trim().isEmpty()) {
            searchResult.update {
                //不能在原始集合中操作, 必须返回新的集合
                SysProManager.getProperties()
            }
            return
        }
        val list = SysProManager.getProperties().filter {
            it.first.contains(text.trim(), true) || it.second.contains(text.trim(), true)
        }
        searchResult.update {
            list.toMutableList()
        }
    }

    /**
     * 搜索结果
     */
    fun searchResult(): StateFlow<List<Pair<String, String>>> {
        return searchResult.asStateFlow()
    }
}